﻿using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.CartoUI;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Framework;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.NetworkAnalysis;
using ESRI.ArcGIS.Output;
using ESRI.ArcGIS.SystemUI;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Windows.Forms;

namespace TubeBurstAnalysis
{
    public partial class FormMain : Form
    {

        /// <summary>
        /// 当前文档
        /// </summary>
        private string m_mapDocumentName = string.Empty;

        /// <summary>
        /// 执行网络追踪分析所使用的接口
        /// </summary>
#pragma warning disable CS0169 // 从不使用字段“FormMain.traceFlowSolverGEN”
        private readonly ITraceFlowSolverGEN traceFlowSolverGEN;
#pragma warning restore CS0169 // 从不使用字段“FormMain.traceFlowSolverGEN”

        /// <summary>
        /// 失灵的阀门列表
        /// </summary>
        private readonly List<IFeature> listFaultyValves;

        /// <summary>
        /// 应关闭的阀门列表
        /// </summary>
        private readonly List<IFeature> listTargetValves;

        /// <summary>
        /// 爆管管道列表
        /// </summary>
#pragma warning disable CS0169 // 从不使用字段“FormMain.listEdgeFlags”
        private readonly List<IEdgeFlag> listEdgeFlags;
#pragma warning restore CS0169 // 从不使用字段“FormMain.listEdgeFlags”

        /// <summary>
        /// 管点列表(仅作为参数)
        /// </summary>
#pragma warning disable CS0169 // 从不使用字段“FormMain.listJunctionFlags”
        private readonly List<IJunctionFlag> listJunctionFlags;
#pragma warning restore CS0169 // 从不使用字段“FormMain.listJunctionFlags”

        /// <summary>
        /// 爆管分析结果
        /// </summary>
        private FormAnalysis formResult = null;

        public FormMain()
        {

            //ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);
            //ESRI.ArcGIS.RuntimeManager.BindLicense(ESRI.ArcGIS.ProductCode.Desktop);
            ESRILicense(); //获取权限
            InitializeComponent(); //初始化组件
            listFaultyValves = new List<IFeature>();
            listTargetValves = new List<IFeature>();
            WindowState = FormWindowState.Maximized;    //最大化窗体 
            //axPageLayoutControl1.Page.FormID = esriPageFormID.esriPageFormA3;
            CopyMapFromMapControlToPageLayoutControl();    // 同步PageLayout

        }

        //改变MapFrame的边框(border):
        private void ChangeBorder()
        {
            //获取视图等相关要素
            IActiveView pActiveView;
            IGraphicsContainer pGraphicsContainer;
            IMap pMap;
            IMapFrame pMapFrame;
            pActiveView = axPageLayoutControl1.PageLayout as IActiveView;
            pMap = pActiveView.FocusMap;
            pGraphicsContainer = pActiveView as IGraphicsContainer;
            pMapFrame = pGraphicsContainer.FindFrame(pMap) as IMapFrame;
            IStyleSelector pStyleSelector;
            //新建一个边框选择器对象
            pStyleSelector = new BorderSelectorClass();
            bool m_bOK;

            m_bOK = pStyleSelector.DoModal(axPageLayoutControl1.hWnd);
            if (!m_bOK)
            {
                return;
            }

            IBorder pBorder;
            //得到一个IBorder对象
            pBorder = pStyleSelector.GetStyle(0) as IBorder;
            pMapFrame.Border = pBorder;
            axPageLayoutControl1.Refresh(esriViewDrawPhase.esriViewBackground, null, null);
        }

        /// <summary>
        /// 获取权限
        /// </summary>
        public static void ESRILicense()
        {
            //RuntimeManager绑定权限
            ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);
            IAoInitialize aoi = new AoInitialize();
            //获取相关产品吗
            esriLicenseProductCode productCode = esriLicenseProductCode.esriLicenseProductCodeEngineGeoDB;
            if (aoi.IsProductCodeAvailable(productCode) == esriLicenseStatus.esriLicenseAvailable)
            {
                //激活相关权限
                aoi.IsProductCodeAvailable(productCode);
                if (aoi.Initialize(productCode) != esriLicenseStatus.esriLicenseCheckedOut)
                {
                    throw new Exception("初始化ArcGIS Engine失败");
                }
            }
            else
            {
                throw new Exception("没有ArcGIS Engine许可");
            }
        }

        //将MapControl中的地图复制到PageLayoutControl中去
        private void CopyMapFromMapControlToPageLayoutControl()
        {
            //获得IObjectCopy接口
            IObjectCopy pObjectCopy = new ObjectCopyClass();
            //获得要拷贝的图层 
            object pSourceMap = axMapControl1.Map;
            //获得拷贝图层
            object pCopiedMap = pObjectCopy.Copy(pSourceMap);
            //获得要重绘的地图 
            object pOverwritedMap = axPageLayoutControl1.ActiveView.FocusMap;
            //重绘pagelayout地图
            pObjectCopy.Overwrite(pCopiedMap, ref pOverwritedMap);
            //生成图例
            InsertNorth(axPageLayoutControl1);
            makeLegend(axPageLayoutControl1.ActiveView, axPageLayoutControl1.PageLayout);
            axPageLayoutControl1.PageLayout.ZoomToWhole();
        }


        private void OpenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //选择需要打开的地图文档，并加载文档中的几何网络
            OpenFileDialog openFilgeDialog = new OpenFileDialog
            {
                Filter = "ArcMap Document (*.mxd)|*.mxd"
            };
            if (openFilgeDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                axMapControl1.LoadMxFile(openFilgeDialog.FileName);
            }
        }

        /// <summary>
        /// 根据R、G、B值获取IColor接口的颜色变量。
        /// </summary>
        /// <param name="red">R分量值</param>
        /// <param name="green">G分量值</param>
        /// <param name="blue">B分量值</param>
        /// <returns>IColor接口的颜色变量</returns>
        public static IColor GetColorByRGBValue(int red, int green, int blue)
        {
            IRgbColor rgbColor = new RgbColorClass
            {
                Red = red,
                Green = green,
                Blue = blue
            };
            return rgbColor;
        }

        /// <summary>
        /// 根据Element名称清除当前视图中的Element
        /// </summary>
        /// <param name="activeView">当前视图</param>
        /// <param name="elementName">Element的名称</param>
        private void ClearElements(IActiveView activeView, string elementName)
        {
            //重置当前视图的指针
            IGraphicsContainer graphicsContainer = activeView as IGraphicsContainer;
            graphicsContainer.Reset();
            IElement element = graphicsContainer.Next();

            //遍历视图的所有元素，查看是否是需要删除的元素，是则删除
            while (element != null)
            {
                if (((IElementProperties)element).Name == elementName)
                {
                    graphicsContainer.DeleteElement(element);
                }

                element = graphicsContainer.Next();
            }

            //刷新
            activeView.Refresh();
        }



        /// <summary>
        /// 筛选失灵阀门
        /// </summary>
        /// <param name="junctionEIDs">已得到的管点分析结果</param>
        /// <param name="netElements">所分析的逻辑网络</param>
        private void GetFaultyValves(IEnumNetEID junctionEIDs, INetElements netElements)
        {
            //准备用来存储查询元素的变量
            int userClassID = 0;
            int userID = 0;
            int userSubID = 0;

            //初始化eid
            int eid = -1;

            //初始化管爆位置连通的节点
            int junctionNum = junctionEIDs.Count;
            junctionEIDs.Reset();

            //遍历连通的管点，如果是阀门，存储
            for (int i = 0; i < junctionNum; i++)
            {
                //eid指向下一位
                eid = junctionEIDs.Next();
                //根据eid查询userClassID、userID、userSubID
                netElements.QueryIDs(eid, esriElementType.esriETJunction, out userClassID, out userID, out userSubID);
                //获取该对象
                IFeature feature = GetFeatureClassByID(userClassID, axMapControl1.Map).GetFeature(userID);
                //获取该对象的附属物字段
                string subs = ConfigurationManager.AppSettings[5];
                string subsID = feature.get_Value(feature.Fields.FindField(subs)).ToString();

                //如果userClassID代表阀门
                if (subsID == "阀门")
                {
                    //应关闭阀门列表添加改阀门元素
                    listFaultyValves.Add(feature);
                }
            }
        }


        /// <summary>
        /// 根据FeatureClass的ID在当前地图中获取FeatureClass。
        /// </summary>
        /// <param name="userClassID">FeatureClass的ID</param>
        /// <param name="map">当前地图</param>
        /// <returns>IFeatureClass接口的变量，或为空</returns>
        private IFeatureClass GetFeatureClassByID(int userClassID, IMap map)
        {
            IFeatureClass featureClass = null;
            for (int i = 0; i < map.LayerCount; i++)
            {
                featureClass = ((IFeatureLayer)map.get_Layer(i)).FeatureClass;
                if (featureClass.FeatureClassID == userClassID)
                {
                    return featureClass;
                }
            }
            return null;
        }

        /// <summary>
        /// 根据FeatureClass的名称获取当前地图中该FeatureClass的ID。
        /// </summary>
        /// <param name="featureClassName">FeatureClass的名称</param>
        /// <param name="map">当前地图</param>
        /// <returns>该FeatureClass的ID</returns>
        private int GetFeatureClassIDByName(string featureClassName, IMap map)
        {
            int id = 0;
            IFeatureLayer featureLayer;
            for (int i = 0; i < map.LayerCount; i++)
            {
                featureLayer = map.get_Layer(i) as IFeatureLayer;
                if (featureLayer.FeatureClass.AliasName == featureClassName)
                {
                    id = featureLayer.FeatureClass.FeatureClassID;
                }
            }
            return id;
        }


        private void generateResult()
        {
            //生成爆管分析结果窗口
            formResult = new FormAnalysis
            {

                //初始化爆管分析结果窗口参数
                listEdgeFlags = new List<IEdgeFlag>(),
                listJunctionFlags = new List<IJunctionFlag>(),
                listFaultyValves = listFaultyValves,
                listTargetValves = listTargetValves,

                //将Map、PageLayout控件进行传递
                AxMapControl = axMapControl1,
                axPageLayoutControl = axPageLayoutControl1,
                MapControlDefault = (axMapControl1.Object as IMapControl2) as IMapControlDefault
            };

            try
            {
                //得到当前几何网络所在的FeatureDataset
                IMap map = axMapControl1.Map;
                IFeatureLayer featureLayer = map.get_Layer(0) as IFeatureLayer;
                IFeatureDataset featureDataset = featureLayer.FeatureClass.FeatureDataset;

                //得到接口转换获得当前所加载的几何网络
                INetworkCollection2 networkCollection2 = featureDataset as INetworkCollection2;

                //通过接口转换得到几何网络的名称，并加载到相应控件中
                formResult.geometricNetwork = networkCollection2.get_GeometricNetwork(0);
                IDataset dataset = formResult.geometricNetwork as IDataset;

                //得到网络分析器所使用的逻辑网络
                formResult.traceFlowSolverGEN = new TraceFlowSolverClass();
                formResult.netSolver = formResult.traceFlowSolverGEN as INetSolver;
                formResult.netSolver.SourceNetwork = formResult.geometricNetwork.Network;
                //显示分析结果窗口
                formResult.Show();
            }
            catch
            {
                MessageBox.Show("请先传入地下管网的mxd文件");
            }

        }

        private void 爆管分析ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            generateResult();
        }

        private void 数据导入帮助ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            MessageBox.Show("");
        }

        private void 联系作者ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("作者QQ:1079858244");
        }

        private void 软件使用帮助ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("请在正确准备好数据，创建相关网络后，使用该软件。");
        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //execute Save Document command
            if (axMapControl1.CheckMxFile(m_mapDocumentName))
            {
                //create a new instance of a MapDocument
                IMapDocument mapDoc = new MapDocument();
                mapDoc.Open(m_mapDocumentName, string.Empty);

                //Make sure that the MapDocument is not readonly
                if (mapDoc.get_IsReadOnly(m_mapDocumentName))
                {
                    MessageBox.Show("Map document is read only!");
                    mapDoc.Close();
                    return;
                }

                //Replace its contents with the current map
                mapDoc.ReplaceContents((IMxdContents)axMapControl1.Map);

                //save the MapDocument in order to persist it
                mapDoc.Save(mapDoc.UsesRelativePaths, false);

                //close the MapDocument
                mapDoc.Close();
            }
        }


        private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ICommand command = new ControlsSaveAsDocCommand();
            command.OnCreate(axMapControl1.Object);
            command.OnClick();
        }


        /// <summary>
        /// pageLayout输出图片
        /// </summary>
        /// <param name="pageLyaoutCtrl">地图布局控件</param>
        /// <returns></returns>
        private void ExportMapToImage(AxPageLayoutControl pageLyaoutCtrl)
        {

            try
            {
                //文件名
                string ImageName = Guid.NewGuid() + "当前显示区域.JPEG";

                //获取文件位置
                string folderPath = GetFolderPath() + "\\";

                //设置文件路径
                string imagePath = folderPath + ImageName;

                // 获取布局视图屏幕分辨率，用于设置输出分辨率
                double iScreenDispalyResolution = pageLyaoutCtrl.ActiveView.ScreenDisplay.DisplayTransformation.Resolution;
                // 导出为图片类型
                IExport pExport = new ExportJPEGClass
                {
                    // 设置输出文件名，为用户在保存窗口设置的文件名
                    ExportFileName = imagePath,
                    // 设置输出分辨率
                    Resolution = (short)iScreenDispalyResolution
                };
                // 获取输出范围  获取视图框架对象，进而得到视图范围
                tagRECT deviceRect = pageLyaoutCtrl.ActiveView.ScreenDisplay.DisplayTransformation.get_DeviceFrame();
                deviceRect.right = deviceRect.left + (deviceRect.right - deviceRect.left) * 4;
                deviceRect.bottom = deviceRect.top + (deviceRect.bottom - deviceRect.top) * 4;
                IEnvelope pDeviceEnvelop = new EnvelopeClass();
                // 设置一个边框范围
                pDeviceEnvelop.PutCoords(deviceRect.left, deviceRect.bottom, deviceRect.right, deviceRect.top);
                // 将打印像素范围 设置给输出对象
                pExport.PixelBounds = pDeviceEnvelop;
                // 设置跟踪取消对象
                ITrackCancel pCancle = new CancelTrackerClass();
                // 进行视图控件的视图输出操作，设置对应参数
                pageLyaoutCtrl.ActiveView.Output(pExport.StartExporting(), (int)pExport.Resolution, ref deviceRect, pageLyaoutCtrl.ActiveView.Extent, pCancle);
                Application.DoEvents();// 启动应用程序
                pExport.FinishExporting();//完成输出

                System.Diagnostics.Process.Start(imagePath);
            }
            catch
            {

            }

        }

        /// <summary>
        /// 获取文件夹
        /// </summary>
        /// <returns>选择的文件夹路径</returns>
        private string GetFolderPath()
        {
            string folderPath = string.Empty;
            using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
            {
                //对话框的标题
                folderBrowserDialog.Description = "选择文件夹";
                //显示对话框
                DialogResult dialogResult = folderBrowserDialog.ShowDialog();
                if (dialogResult == DialogResult.OK)
                {
                    //获取选择的文件夹的路径
                    folderPath = folderBrowserDialog.SelectedPath;
                }
            };
            return folderPath;
        }

        private void 打印布局ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExportMapToImage(axPageLayoutControl1);
        }

        private void 改变布局边框ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChangeBorder();
        }

        /// <summary>
        /// 生成图例
        /// </summary>
        private void makeLegend(IActiveView activeView, IPageLayout pageLayout)
        {
            UID id = new UID
            {
                Value = "esriCarto.Legend"
            };
            IGraphicsContainer graphicsContainer = pageLayout as IGraphicsContainer;
            IMapFrame mapFrame = graphicsContainer.FindFrame(activeView.FocusMap) as IMapFrame;
            //根据唯一标识符，创建与之对应的MapSurroundFrame
            IMapSurroundFrame mapSurroundFrame = mapFrame.CreateSurroundFrame(id, null);
            //获取pageLayout中的图例元素

            // ESRI.ArcGIS.Carto.IElement element = null;

            //设置MapSurroundFrame背景
            ISymbolBackground symbolBackground = new SymbolBackgroundClass();
            IFillSymbol fillSymbol = new SimpleFillSymbolClass();
            ILineSymbol lineSymbol = new SimpleLineSymbolClass
            {
                Color = GetColorByRGBValue(0, 0, 1)
            };
            fillSymbol.Color = GetColorByRGBValue(240, 240, 240);
            fillSymbol.Outline = lineSymbol;
            symbolBackground.FillSymbol = fillSymbol;
            mapSurroundFrame.Background = symbolBackground;
            //添加图例
            IElement pElement = mapSurroundFrame as IElement;
            //设置图例包络线
            IEnvelope envelope = new EnvelopeClass();
            //通过当前地图框架得到相对位置
            IElement mapElement = mapFrame as IElement;
            IEnvelope mapEnv = mapElement.Geometry.Envelope;
            envelope.PutCoords(mapEnv.XMax - 3, mapEnv.YMin, mapEnv.XMax, mapEnv.YMin + 0.8);
            pElement.Geometry = envelope;
            ((IElementProperties)pElement).Name = "Result";
            IMapSurround mapSurround = mapSurroundFrame.MapSurround;
            ILegend legend = mapSurround as ILegend;
            legend.ClearItems();
            //legend.Format.DefaultPatchHeight = 1.5 * legend.Format.DefaultPatchHeight;
            //legend.Format.DefaultPatchWidth = 1.2 * legend.Format.DefaultPatchHeight;
            if (legend.Title == null)
            {
                legend.Title = "图例";
            }
            for (int i = 0; i < activeView.FocusMap.LayerCount; i++)
            {
                try
                {
                    ILegendItem legendItem = new HorizontalLegendItemClass
                    {
                        Layer = activeView.FocusMap.get_Layer(i),//获取添加图例关联图层
                        ShowDescriptions = false,
                        Columns = 1,
                        ShowHeading = true,
                        ShowLabels = true
                    };
                    legend.AddItem(legendItem);//添加图例内容
                }
                catch { }

            }

            graphicsContainer.AddElement(pElement, 0);
            activeView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);


        }

        /// <summary>
        /// 给页面布局控件添加指北针
        /// </summary>
        /// <param name="pageLayout"></param>
        public static void InsertNorth(AxPageLayoutControl axPageLayout)
        {
            IElement pElement = axPageLayout.FindElementByName("MarkerNorthArrow");
            if (pElement != null)
            {
                axPageLayout.ActiveView.GraphicsContainer.DeleteElement(pElement);  //删除已经存在的图例
            }
            IPageLayout pPageLayout = axPageLayout.PageLayout;
            IGraphicsContainer pGraphicsContainer = pPageLayout as IGraphicsContainer;
            IActiveView pActiveView = pPageLayout as IActiveView;
            UID pID = new UIDClass
            {
                Value = "esriCore.MarkerNorthArrow"
            };

            IMapFrame pMapFrame = pGraphicsContainer.FindFrame(pActiveView.FocusMap) as IMapFrame;
            if (pMapFrame == null)
            {
                return;
            }

            IMapSurroundFrame pMapSurroundFrame = pMapFrame.CreateSurroundFrame(pID, null);
            if (pMapSurroundFrame == null)
            {
                return;
            }

            IElement mapElement = pMapFrame as IElement;
            IEnvelope mapEnv = mapElement.Geometry.Envelope;
            IEnvelope pEnv = new EnvelopeClass();
            pEnv.PutCoords(mapEnv.XMax, mapEnv.YMax, mapEnv.XMax - 3, mapEnv.YMax - 3);
            pElement = (IElement)pMapSurroundFrame;
            pElement.Geometry = pEnv;
            pMapSurroundFrame.MapSurround.Name = "MarkerNorthArrow";
            INorthArrow pNorthArrow = pMapSurroundFrame.MapSurround as INorthArrow;
            pGraphicsContainer.AddElement(pElement, 0);
        }

        private void 清空ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //清除爆管分析的各类标识和结果，并清空爆管和阀门元素记录

            //清除显示结果
            ClearElements(axMapControl1.ActiveView, "BurstPipePoint");
            ClearElements(axMapControl1.ActiveView, "Result");
        }

        private void axMapControl1_OnMapReplaced(object sender, IMapControlEvents2_OnMapReplacedEvent e)
        {
            //get the current document name from the MapControl
            m_mapDocumentName = axMapControl1.DocumentFilename;

            //if there is no MapDocument, diable the Save menu and clear the statusbar
            if (m_mapDocumentName == string.Empty)
            {
                保存ToolStripMenuItem.Enabled = false;
                toolStripStatusLabel1.Text = string.Empty;
            }
            else
            {
                //enable the Save manu and write the doc name to the statusbar
                保存ToolStripMenuItem.Enabled = true;
                toolStripStatusLabel1.Text = System.IO.Path.GetFileName(m_mapDocumentName);
            }

            CopyMapFromMapControlToPageLayoutControl();//调用地图复制函数

        }

        private void axMapControl1_OnAfterScreenDraw_1(object sender, IMapControlEvents2_OnAfterScreenDrawEvent e)
        {
            //根据MapControl的视图范围，确定PageLayoutControl的视图范围
            //CopyMapFromMapControlToPageLayoutControl();
            //获得IActiveView接口
            IActiveView pPageLayoutView = (IActiveView)axPageLayoutControl1.ActiveView.FocusMap;
            //获得IDisplayTransformation接口
            IDisplayTransformation pDisplayTransformation = pPageLayoutView.ScreenDisplay.DisplayTransformation;
            //设置可视范围
            pDisplayTransformation.VisibleBounds = axMapControl1.Extent;
            axPageLayoutControl1.ActiveView.Refresh(); //刷新地图
        }

        private void axMapControl1_OnViewRefreshed(object sender, IMapControlEvents2_OnViewRefreshedEvent e)
        {
            /**
            axTOCControl1.Refresh();
            axPageLayoutControl1.ActiveView.Clear();
            CopyMapFromMapControlToPageLayoutControl();
            **/
        }

        private void axTOCControl1_OnDoubleClick(object sender, ITOCControlEvents_OnDoubleClickEvent e)
        {
            IFeatureLayer pLayer = null;
            esriTOCControlItem item = esriTOCControlItem.esriTOCControlItemNone;
            IBasicMap bmp = null;
            ILayer layer = null;
            object unk = null;
            object data = null;
            axTOCControl1.HitTest(e.x, e.y, ref item, ref bmp, ref layer, ref unk, ref data);
            pLayer = layer as IFeatureLayer;
            if (item == esriTOCControlItem.esriTOCControlItemLayer && pLayer != null)
            {
                (axMapControl1.Map as IActiveView).Extent = pLayer.AreaOfInterest;
                (axMapControl1.Map as IActiveView).PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            ClearElements(axMapControl1.ActiveView, "BurstPipePoint");
        }

        private void axTOCControl1_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e)
        {

        }

        //设置数据源
        private void SetDataSource()

        {
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog
                {
                    Title = "打开数据库文件",
                    CheckFileExists = true
                };
                openFileDialog.ShowDialog();
                string sTargetPath = openFileDialog.FileName;
                //创建一个工作空间

                IWorkspaceFactory pWorkFactory = new AccessWorkspaceFactoryClass();

                IWorkspace pWorkspace = pWorkFactory.OpenFromFile(sTargetPath, 0);

                //获取工作空间中的所有Dataset

                IEnumDataset pEnumDataSet = pWorkspace.get_Datasets(esriDatasetType.esriDTFeatureDataset);

                IDataset pDataSet = pEnumDataSet.Next();

                ISpatialReference pRef = (pDataSet as IGeoDataset).SpatialReference;

                string sDistrictCode = string.Empty;

                string sScale = string.Empty;

                if (pDataSet != null)

                {

                    UID uid = new UIDClass
                    {
                        Value = "{" + typeof(IFeatureLayer).GUID.ToString() + "}"
                    };

                    IEnumLayer pEnumLayer = axMapControl1.Map.get_Layers(uid, true);

                    IFeatureLayer pFeaLyr = pEnumLayer.Next() as IFeatureLayer;

                    IFeatureWorkspace pFeaClsWks = pWorkspace as IFeatureWorkspace;

                    while (pFeaLyr != null)

                    {
                        string sDsName = ((pFeaLyr as IDataLayer).DataSourceName as IDatasetName).Name;

                        if ((pWorkspace as IWorkspace2).get_NameExists(esriDatasetType.esriDTFeatureClass, sDsName))

                        {


                            pFeaLyr.FeatureClass = pFeaClsWks.OpenFeatureClass(sDsName);

                            pFeaLyr.Name = pFeaLyr.Name;

                        }

                        pFeaLyr = pEnumLayer.Next() as IFeatureLayer;

                    }

                }
                axMapControl1.Refresh();
                axTOCControl1.Refresh();
            }
            catch
            {
                return;
            }



        }

        private void 设置数据源ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetDataSource();
        }

        private void 查看帮助ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //输入帮助文档路径
            string helpfile = "help.chm";
            Help.ShowHelp(this, helpfile);
        }

        private void 爆管分析ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            generateResult();
        }

        private void 渲染所有点ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //获得图层一
            IFeatureClass featureClass = ((IFeatureLayer)axMapControl1.Map.get_Layer(0)).FeatureClass;
            IFeatureCursor featureCursor = featureClass.Search(null, true);
            IFeature feature;
            int i = 101;
            //遍历所有feature
            while ((feature = featureCursor.NextFeature()) != null)
            {
                //绘制并显示管线标识
                ICharacterMarkerSymbol characterMarkerSymbol = new CharacterMarkerSymbol
                {
                    CharacterIndex = i++,
                    Size = 24,
                    Color = GetColorByRGBValue(255, 0, 0)
                };


                IElement element = new MarkerElementClass
                {
                    Geometry = feature.Shape
                };
                ((IMarkerElement)element).Symbol = characterMarkerSymbol;
                ((IElementProperties)element).Name = "点";
                ((IGraphicsContainer)axMapControl1.ActiveView).AddElement(element, 0);
            }

            axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, axMapControl1.ActiveView.Extent);
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //将设置的失灵阀门设置为非失灵

            for (int i = 0; i < listFaultyValves.Count; i++)
            {
                //获取失灵阀门
                IFeature selectedPoint = listFaultyValves[i];
                //获取工作空间
                IDataset dataset = selectedPoint.Class as IDataset;
                IWorkspace workspace = dataset.Workspace;
                IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;
                workspaceEdit.StartEditing(false);
                workspaceEdit.StartEditOperation();
                //修改属性
                int fieldID = selectedPoint.Fields.FindField("ENABLED");
                selectedPoint.set_Value(fieldID, 0);
                selectedPoint.Store();
                //停止编辑
                workspaceEdit.StopEditOperation();
                workspaceEdit.StopEditing(true);
            }


        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormAbout form = new FormAbout();
            form.Show();
        }
    }
}
